package com.hwadee.teachingprocessmanagementsystem.controller.base;

import com.hwadee.teachingprocessmanagementsystem.dto.LoginUserDto;
import com.hwadee.teachingprocessmanagementsystem.entity.User;
import com.hwadee.teachingprocessmanagementsystem.service.base.RedisService;
import com.hwadee.teachingprocessmanagementsystem.service.login.LoginService;
import com.hwadee.teachingprocessmanagementsystem.util.ColorLoggerUtils;
import com.hwadee.teachingprocessmanagementsystem.util.result.DataResult;
import com.hwadee.teachingprocessmanagementsystem.util.result.code.Code;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2024-07-11 14:20:03
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private LoginService loginService;
    @Resource
    private RedisService redisService;
    private ColorLoggerUtils logger = ColorLoggerUtils.getLogger(UserController.class);

    @PostMapping("login")
    public DataResult<Object> login(@RequestBody User user) {
        logger.info("Verifying user:" + user.getUid());
        User verifyUser = this.loginService.verifyUser(user);
        if (verifyUser == null) {
            // 登录失败
            logger.info("Login failed");
            return DataResult.errByErrCode(Code.LOGIN_ERROR);
        }
        logger.info("Login succeed");
        logger.info("Verified user:" + user.getUid());
        String token = this.loginService.getToken(verifyUser);
        logger.info("Verified token:" + token);
        // 设置token过期时间为2小时
        // 设置token为键，方便查找
        redisService.storeValue(token, String.valueOf(System.currentTimeMillis()), 2*60*60);
        LoginUserDto loginUserDto = loginService.getLoginUserDto(verifyUser);

        DataResult result = DataResult.successByData(loginUserDto);
        return result;
    }

    @RequestMapping("logout")
    public DataResult<Object> logout(@RequestParam("token") String token) {
        Object cacheValue = this.redisService.getCacheValue(token);
        if (cacheValue != null) {
            this.redisService.removeValue(token);
        }
        // 如果Redis存储有token，则删除，没有表示token过期或者已经登出
        return DataResult.successByMessage("登出成功",null);
    }
}

